<template>
    <section>
        <!--工具条-->
        <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
            <el-form :inline="true" :model="filters">
                <el-form-item>
                    <el-input v-model="filters.keyword" placeholder="关键词"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" v-on:click="getDepartments">查询</el-button>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="handleAdd">新增</el-button>
                </el-form-item>
            </el-form>
        </el-col>

       <!-- private String sn;
        private String name;
        private String dirPath;
        private Integer state;
        /*部门经理 和员工关联*/
        private Employee manager;
        private Long parent_id;
        /*上级部门*/
        private Department parent;-->
        <!--列表-->
        <el-table :data="departments" highlight-current-row v-loading="listLoading" @selection-change="selsChange" style="width: 100%;">
            <el-table-column type="selection" width="55">
            </el-table-column>
            <el-table-column type="index" width="60">
            </el-table-column>
            <el-table-column prop="name" label="名称" width="160" sortable>
            </el-table-column>
            <el-table-column prop="sn" label="标识" width="160" sortable>
            </el-table-column>
            <!--:formatter="formatState"-->
            <el-table-column prop="state" label="状态" width="150"  sortable>
                <!--这里我们给状态定义一个颜色为了视觉效果更好，经测试只能写在这里，和下面的操作一样
                scope.row是拿到当前行的值-->
                <template scope="scope">
                    <span style="color: green" v-if="scope.row.state==0">正常</span>
                    <span style="color: red" v-else-if="scope.row.state==-1">禁用</span>
                    <span style="color: #475669" v-else>未知</span>
                </template>
            </el-table-column>
            <!--根据传回前台的信息为了要显示关联对象我们是找manager对象里面的username,下面如此-->
            <el-table-column prop="manager.username" label="经理" width="120" sortable>
            </el-table-column>
            <el-table-column prop="parent.name" label="上级部门" width="120" sortable>
            </el-table-column>
            <el-table-column label="操作" width="150">
                <template scope="scope">
                    <el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
                    <el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!--工具条-->
        <el-col :span="24" class="toolbar">
            <el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
            <el-pagination layout="prev, pager, next" @current-change="handleCurrentChange" :current-page="page" :page-size="pageSize" :total="total" style="float:right;">
            </el-pagination>
        </el-col>

        <!--添加或编辑界面-->
        <el-dialog :title="title" :visible.sync="departmentFormVisible" :close-on-click-modal="false">
            <el-form :model="departmentForm" label-width="80px" :rules="departmentFormRules" ref="departmentForm">
                <!--这里的prop是为了下面的规则用来对应的也就是必须输入啥的-->
                <el-form-item label="姓名" prop="name">
                    <el-input v-model="departmentForm.name" auto-complete="off"></el-input>
                </el-form-item>
                <el-form-item label="标识" prop="sn">
                    <el-input v-model="departmentForm.sn" auto-complete="off"></el-input>
                </el-form-item>
                <el-form-item label="状态">
                    <el-radio-group v-model="departmentForm.state">
                        <el-radio class="radio" :label="0">正常</el-radio>
                        <el-radio class="radio" :label="-1">禁用</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="经理" prop="manager">
                    <!--关联查询我们使用下拉级联表来完成-->
                    <!--el-option选项-->
                    <!--v-for="item in employees"多个选项，所以进行遍历-->
                    <!--:value="item"> 传递到后台的值对象-->
                    <!--这里需要和表单的数据双向绑定 v-model="departmentForm.manager"-->
                    <!--value-key="id" 只要:value是对象，必须要添加所以key必须要添加-->
                    <!--:label="item.username" 显示的内容，我们只需要经理的username展示就好-->
                    <el-select v-model="departmentForm.manager" value-key="id" clearable placeholder="请选择">
                        <el-option
                                v-for="item in employees"
                                :key="item.id"
                                :label="item.username"
                                :value="item">
                            <span style="float: left">{{ item.username }}</span>
                            <span style="float: right; color: #8492a6; font-size: 13px">{{item.phone}}</span>
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="上级部门" prop="parent">
                    <!--我们需要在下面双向绑定v-model我们需要展示的部门树，层层往下
                        :options可选项数据源,我们这里需要传上我们找到的所有部门及下面的子部门信息也就是部门树
                        :options键名可通过 Props 属性配置
                        checkStrictly:是否严格的遵循父子不互相关联的做法，默认为 false
                        label name和后台的部门名称的数据库字段名展示的数据；一定要加''
                        value传到后台的数据；一定要加''
                    -->
                    <el-cascader
                            v-model="departmentForm.parent"
                            :options="deptTree"
                            :props="{
                                checkStrictly:true,
                                label:'name',
                                value:'id'
                            }"
                            clearable></el-cascader>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click.native="departmentFormVisible = false">取消</el-button>
                <el-button type="primary" @click.native="save" :loading="departmentLoading">提交</el-button>
            </div>
        </el-dialog>


    </section>
</template>

<script>
    import util from '../../common/js/util'
    //import NProgress from 'nprogress'
    import { getDepartmentListPage, removeDepartment, batchRemoveDepartment, editDepartment, addDepartment } from '../../api/api';

    export default {
        data() {
            return {
                filters: {
                    keyword: ''
                },
                departments: [],
                total: 0,
                page: 1,
                //一页显示多少条
                pageSize:10,
                listLoading: false,
                sels: [],//列表选中列

                departmentFormVisible: false,//编辑界面是否显示
                departmentLoading: false,
                departmentFormRules: {
                    name: [
                        { required: true, message: '请输入姓名', trigger: 'blur' }
                    ],
                    sn: [
                        { required: true, message: '请输入标识', trigger: 'blur' }
                    ]
                },
                title:"",
                departmentForm: {
                    id:null,
                    name: '',
                    sn: '',
                    state: 0,
                    manager: {},
                    parent: {}
                },
                // 关联属性处理
                employees:[],
                deptTree:[]

            }
        },
        methods: {
            // //状态显示转换-不能上色
            // formatState: function (row, column) {
            // 	return row.state == 0 ? '正常' : row.state == -1 ? '禁用' : '未知';
            // },
            search() {
                //查询完，原来分页条件已经没用了，要跑到第一页去
                this.page = 1;
                this.getDepartments();
            }
            ,
            handleCurrentChange(val) {
                this.page = val;
                this.getDepartments();
            },
            //获取部门列表
            getDepartments() {
                let para = {
                    currentPage: this.page,
                    keyword: this.filters.keyword
                };
                this.listLoading = true;
                this.$http.post("/department",para)
                    .then(result=>{
                        result = result.data; //取出data这一层
                        this.total = result.totals;
                        this.departments = result.rows;
                        this.listLoading = false;
                    })
                    .catch(result=>{
                        alert("系统错误！")
                    })
            },

            //获取员工列表
            getEmployees() {
                this.$http.get("/employee")
                    .then(result=>{
                        result=result.data;
                       if (result){
                           this.employees=result;
                       }
                    })
                    .catch(result=>{
                        alert("系统错误！")
                    })
            },

            //获取部门树
            getDeptTree() {
                this.$http.get("/department/deptTree") //查询部门树
                    .then(result=>{
                        result=result.data;
                        if (result){
                            this.deptTree=result;
                        }
                    })
                    .catch(result=>{
                        alert("系统错误！")
                    })
            },
            //删除
            handleDel: function (index, row) {
                this.$confirm('确认删除该记录吗?', '焜焜提示', {
                    type: 'warning'
                }).then(() => {
                    this.listLoading = true;
                    /*//NProgress.start();
                    let para = { id: row.id };
                    removeDepartment(para).then((res) => {
                        this.listLoading = false;
                        //NProgress.done();
                        this.$message({
                            message: '删除成功',
                            type: 'success'
                        });
                        this.getDepartments();
                    });*/
                //    由于后端的删除接口使根据resultful风格来编码的，所以我们这里要给他弄成相对应的风格
                    let url = "/department/"+row.id;
                    this.$http.delete(url)
                        .then(result=> {
                            result=result.data;//{sucess:false,message}
                            //去除忙等框
                            this.listLoading = false;

                            if (result.success) {
                                //删除成功我们跳回第一页，防止有那一页还没数据继续停留的bug
                                this.page=1;
                                //提示
                                this.$message({
                                    message: '删除成功',
                                    type: 'success'
                                });
                                //重新查找数据
                                this.getDepartments();
                            }else {
                                //提示
                                this.$message({
                                    message: result.message,
                                    type: 'error'
                                });
                                //重新查找数据
                                this.getDepartments();
                            }
                            }
                        )
                        .catch(result=>{
                            //去除忙等框
                            this.listLoading = false;
                            //提示
                            this.$message({
                                message: '系统错误',
                                type: 'error'
                            });
                        })
                }).catch(() => {

                });
            },
            //显示编辑界面
            handleEdit: function (index, row) {
                this.departmentFormVisible = true;// 显示编辑框
                this.title="编辑";
                //需要加载部门树，
                // 不能在页面加载的时候获取，因为在该页面改变部门数据，没有去重新获取,每次获取的都是原来的数据。每次打开窗口重新加载就ok了。
                this.getDeptTree();
                //Object.assign({}, row) //克隆
                this.departmentForm = Object.assign({}, row);//回显,因为双向绑定了，修改的话会同时影响到界面的值，所以我们正在修改之前先复制一份
                //先定义一个数组可以装上我们需要转换为这样的this.departmentForm.parent=[2,11]数据
                    let dirPath = row.dirPath;//2/5/11
                let tem = [];
                //在分割之前先做一个空值判断
                if(dirPath) {
                    //然后我们将dirpath分割在一个个存入到新的数组转换类似上面的[2,5,11]
                    let dirPaths = dirPath.trim().split("/");//["","2","5","11"]
                    //这是我们通过分割后的结果分析，我们不要第一个，也不要最后一个自己本身的所以下面的i从1开始计数,不要最后一个dirPaths.length-1
                    for(let i=1; i<dirPaths.length-1;i++) {
                        //存入新的数组我们下标必须从0开始所以i-1
                        tem[i-1] = parseInt(dirPaths[i])//我们可以看到分割之后的数组转换成了字符串的形式所以我们再parseInt转换为int类型
                    }
                }
                //最后根据dirPath构造数组this.departmentForm.parent=[2,11]
                this.departmentForm.parent = tem;
            },
            //显示新增界面
            handleAdd: function () {
                this.title = "新增";
                this.departmentForm = { //清空
                    id:null,
                    name: '',
                    sn: '',
                    state: 0,
                    manager: {},
                    parent: {}
                };
                //需要加载部门树，
                // 不能在页面加载的时候获取，因为在该页面改变部门数据，没有去重新获取,每次获取的都是原来的数据。每次打开窗口重新加载就ok了。
                this.getDeptTree();
                //需要所有的数据都加载完毕再显示新增框，这样才符合逻辑
                this.departmentFormVisible = true; //显示新增框
            },
            //保存
            save: function () {
                // 表单上定义了ref="departmentForm"
                this.$refs.departmentForm.validate((valid) => {
                    if (valid) {
                        this.$confirm('确认保存吗？', '温馨提示', {}).then(() => {
                            this.departmentLoading = true;
                            /*//NProgress.start();
                            let para = Object.assign({}, this.departmentForm);
                            para.birth = (!para.birth || para.birth == '') ? '' : util.formatDate.format(new Date(para.birth), 'yyyy-MM-dd');
                            editUser(para).then((res) => {
                                this.departmentLoading = false;
                                //NProgress.done();
                                this.$message({
                                    message: '提交成功',
                                    type: 'success'
                                });
                                this.$refs['departmentForm'].resetFields();
                                this.departmentFormVisible = false;
                                this.getDepartments();
                            });*/
                           //我们拷贝一份数据为了传递给后端处理添加和修改操作
                            let para  = Object.assign({},this.departmentForm);
                            //因为提交的话直接上传再上级部门前台传到后台的是一个数组，所以我们需要加昂起转换成一个对象，需要对数据进行一个处理
                            let arrays = para.parent;//这是前端转到后台的形式【2，11】
                            //后台要的是department对象
                            para.parent = {"id":arrays[arrays.length-1]}//我们从数组中取出的最后一个id就是他在自己的id
                            //开始操作数据发请求
                            this.$http.put("/department",para)
                                .then(result=>{
                                    result=result.data;
                                    if (result.success){
                                        //成功就去除忙等狂
                                        this.departmentLoading = false;
                                        this.$message({
                                            message: '提交成功',
                                            type: 'success'
                                        });
                                        //重新获取数据
                                        this.getDepartments();
                                    }else {
                                        //失败就去除忙等狂
                                        this.departmentLoading = false;
                                        this.$message({
                                            message: result.message,
                                            type: 'error'
                                        });
                                        //重新获取数据
                                        this.getDepartments();
                                    }
                                    this.departmentFormVisible = false;
                                })
                                .catch(result=>{
                                    this.departmentLoading = false;
                                    alert("系统错误")
                                })
                        });
                    }
                });
            },
            //所有选中对象都会传进来
            selsChange: function (sels) {
                this.sels = sels;
            },
            //批量删除
            batchRemove: function () {
                //我们不需要toString，因为我们直接返回一个数组给后台进行遍历一个个删除
                var ids = this.sels.map(item => item.id);
                this.$confirm('确认删除选中记录吗？', '提示', {
                    type: 'warning'
                }).then(() => {
                    this.listLoading = true;
                    //NProgress.start();
                    // let para = { ids: ids };
                   /* batchRemoveDepartment(para).then((res) => {
                        this.listLoading = false;
                        //NProgress.done();
                        this.$message({
                            message: '删除成功',
                            type: 'success'
                        });
                        this.getDepartments();
                    });*/
                    //传递数组参数到后台批量删除，不需要let para = { ids: ids };
                   this.$http.patch("/department",ids)
                       .then(result=>{
                           result = result.data;
                           //去除忙等框
                           this.listLoading = false;
                           if (result){
                               //成功提示
                               this.$message({
                                   message: '删除成功',
                                   type: 'success'
                               });
                               this.page =1; //删除后跳转第一页
                               //从新获取数据
                               this.getDepartments();
                           }else {
                               //去除忙等框
                               this.listLoading = false;
                               //失败提示
                               this.$message({
                                   message: '删除成功'+ result.message,
                                   type: 'error'
                               });
                               //从新获取数据
                               this.getDepartments();
                           }
                       })
                       .catch(result=>{
                           alert("系统错误");
                           this.listLoading = false;
                       })

                }).catch(() => {

                });
            }
        },
        mounted() {
            this.getDepartments();
            this.getEmployees();
        }
    }

</script>

<style scoped>

</style>